﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using LibraryMusicStore;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraEditors.ViewInfo;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraGrid.Columns;

namespace AppMusicStore
{
    public partial class frmArtist : DevExpress.XtraEditors.XtraForm
    {
        IRepository<Artist> artistRepository ;

        public frmArtist()
        {
            InitializeComponent();
        }

        private void frmAlbum_Load(object sender, EventArgs e)
        {
            try
            {
                artistRepository = new Repository<Artist>();
                RetrieveData();
            }
            catch (Exception ex)
            {
                Common.ShowErrorBox(ex.Message);
            }
        }

        private void RetrieveData()
        {
            //var a = new Repository<Album>();
            bindingSource1.DataSource = artistRepository.GetAll()
                .OrderByDescending(g => g.ArtistId);
        }

        private void Editor_Click(object sender, EventArgs e)
        {
            try
            {
                var frm = new frmArtistEditor();
                frm.ArtistRepository = artistRepository;

                if (sender.GetType().Name == "SimpleButton")
                    frm.Text = "Thêm nghệ sĩ";
                else
                {
                    if (gridView1.GetFocusedRowCellValue("ArtistId") == null)
                        return;
                    frm.Text = "Sửa nghệ sĩ";
                    frm.id = Convert.ToInt32(gridView1
                        .GetFocusedRowCellValue("ArtistId"));
                }

                if (frm.ShowDialog(this) == DialogResult.OK)
                {
                    RetrieveData();

                    gridView1.FocusedRowHandle = gridView1
                        .LocateByValue("ArtistId", frm.id);

                }

                frm.Dispose();
            }
            catch (Exception ex)
            {
                Common.ShowErrorBox(ex.Message);
            }
        }

        #region "Context menu item"
        private void InsertToolStripMenuItem_Click(object sender, EventArgs e)
        {
            btnInsert.PerformClick();
        }

        private void EditToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Editor_Click(this.repositoryItemButtonEdit, new EventArgs());
        }

        private void DeleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            btnDelete_Click();
        }
        #endregion

        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
            if (gridView1.GetFocusedRowCellValue("ArtistId") == null)
                ChangeVisibleToolTip(false);
            else
                ChangeVisibleToolTip(true);
        }

        private void ChangeVisibleToolTip(bool p)
        {
            EditToolStripMenuItem.Visible = p;
            DeleteToolStripMenuItem.Visible = p;
        }

        private void btnDelete_Click()
        {
            try
            {
                DialogResult rs;
                Artist artist;

                if (gridView1.SelectedRowsCount > 1)
                {
                    int[] iRows = gridView1.GetSelectedRows();

                    rs = Common.ShowQuestionBox("Xóa các nghệ sĩ đã chọn?", "okcancel");

                    string str = "";

                    if (rs == DialogResult.OK)
                    {
                        foreach (var item in iRows)
                        {
                            artist = artistRepository.GetById(
                                Convert.ToInt32(gridView1.GetRowCellValue(item, "ArtistId")));

                            if (artist.Albums.Where(a =>
                                        a.Deleted == false ||
                                        a.Deleted == null).Count() == 0)
                                artistRepository.DeleteOnSubmit(artist);
                            else
                                str += artist.Name + ", ";
                        }

                        if (str.Length != 0)
                            Common.ShowErrorBox(str + " còn chứa album.");
                        

                        artistRepository.SubmitChanges();
                        RetrieveData();
                    }
                    return;
                }

                if (gridView1.GetFocusedRowCellValue("ArtistId") == null)
                    return;

                artist = artistRepository.GetById(
                    Convert.ToInt32(gridView1
                    .GetFocusedRowCellValue("ArtistId")));

                if (artist.Albums.Where(a => 
                                        a.Deleted == false ||
                                        a.Deleted == null).Count() == 0)
                {
                    rs = Common.ShowQuestionBox("Xóa nghệ sĩ " + artist
                    .Name + " ?", "okcancel");

                    if (rs == DialogResult.OK)
                    {
                        artistRepository.DeleteOnSubmit(artist);
                        artistRepository.SubmitChanges();

                        RetrieveData();

                        Common.ShowInfomationBox("Đã xóa");
                    }
                }
                else
                    Common.ShowErrorBox(artist.Name + " còn chứa album.");
            }
            catch (Exception ex)
            {
                Common.ShowErrorBox(ex.Message);
            }
        }

        private void gridView1_MouseDown(object sender, MouseEventArgs e)
        {
            try
            {
                if (Control.ModifierKeys != Keys.None) return;

                var view = sender as GridView;

                if (view.SelectedRowsCount < 2) return;

                GridHitInfo hi = view.CalcHitInfo(new Point(e.X, e.Y));

                if (e.Button == MouseButtons.Left && hi.RowHandle >= 0 &&
                    hi.InRowCell && hi.Column.Name == "colDelete")
                {
                    btnDelete_Click();
                }
            }
            catch (Exception)
            {
                return;
            }
        }

        private void repositoryItemButtonDelete_Click(object sender, EventArgs e)
        {
            btnDelete_Click();
        }
    }
}